<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">分类管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <i class="fas fa-plus mr-2"></i>
        添加分类
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <el-input
          v-model="searchForm.name"
          placeholder="分类名称"
          clearable
        >
          <template #prefix>
            <i class="fas fa-tag text-gray-400"></i>
          </template>
        </el-input>
        <el-select v-model="searchForm.status" placeholder="状态" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option label="正常" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
        <div class="flex space-x-2">
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-2"></i>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 分类列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <el-table
        :data="categoryList"
        v-loading="loading"
        stripe
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :default-expand-all="false"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="图标" width="80" align="center">
          <template #default="{ row }">
            <i :class="row.icon" class="text-lg text-primary"></i>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="分类名称" width="200" align="center">
          <template #default="{ row }">
            <div class="flex items-center" style="justify-content: center;">
              <span :class="{ 'text-gray-600': row.parentId !== 0 }">
                {{ row.name }}
              </span>
              <el-tag v-if="row.parentId !== 0" size="small" type="info" class="ml-2">
                子分类
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sortOrder" label="排序" width="100" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="220" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right" align="center" >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              <i class="fas fa-edit mr-1"></i>
              编辑
            </el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleCategoryStatus(row)"
            >
              <i class="fas fa-toggle-on mr-1"></i>
              {{ row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              v-if="row.parentId === 0"
              size="small"
              type="info"
              @click="showAddSubDialog(row)"
            >
              <i class="fas fa-plus mr-1"></i>
              添加子分类
            </el-button>
            <el-button size="small" type="danger" @click="deleteCategory(row)">
              <i class="fas fa-trash mr-1"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      @close="resetForm"
    >
      <!-- 表单内容 -->
      <el-form
        ref="formRef"
        :model="categoryForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-select v-model="categoryForm.parentId" placeholder="请选择父分类" style="width: 100%">
            <el-option label="顶级分类" :value="0" />
            <el-option
              v-for="category in topCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类图标" prop="icon">
          <el-input
            v-model="categoryForm.icon"
            placeholder="例如: fas fa-book"
            @input="validateIcon"
          >
            <template #prepend>
              <i :class="categoryForm.icon || 'fas fa-tag'" class="w-4"></i>
            </template>
            <template #append>
              <el-button
                @click="openFontAwesome"
                type="primary"
                size="small"
                style="border: none;"
              >
                <i class="fas fa-external-link-alt mr-1"></i>
                选择图标
              </el-button>
            </template>
          </el-input>
          <div v-if="iconValidationMessage" class="text-xs mt-1" :class="iconValidationClass">
            {{ iconValidationMessage }}
          </div>
        </el-form-item>
        <el-form-item label="排序值" prop="sortOrder">
          <el-input-number
            v-model="categoryForm.sortOrder"
            :min="0"
            :max="999"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="categoryForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>

      <!-- 分类图标添加方法说明 -->
      <div class="mt-6 bg-blue-50 rounded-lg p-4 border border-blue-200">
        <h4 class="font-bold text-blue-800 mb-3 flex items-center">
          <i class="fas fa-info-circle text-blue-500 mr-2"></i>
          分类图标添加方法
        </h4>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 text-sm">
          <!-- 图标库操作步骤 -->
          <div>
            <!-- 操作步骤 -->
            <div class="bg-white rounded-lg p-4 border border-gray-200 mb-4">
              <h5 class="font-semibold text-gray-700 mb-3 flex items-center">
                <i class="fas fa-clipboard-list text-blue-500 mr-2"></i>
                操作步骤：
              </h5>
              <ol class="list-decimal list-inside space-y-2 text-gray-600 text-sm">
                <li>访问 <a href="https://fontawesome.com/search" target="_blank" class="text-blue-600 hover:text-blue-800 underline font-medium">FontAwesome图标库</a></li>
                <li>搜索您需要的图标关键词</li>
                <li>点击图标查看详情</li>
                <li>复制图标的CSS类名</li>
                <li>在右侧输入框中填写完整类名</li>
              </ol>
            </div>

            <!-- 填写格式 -->
            <div class="bg-white rounded-lg p-4 border border-gray-200">
              <h5 class="font-semibold text-gray-700 mb-3 flex items-center">
                <i class="fas fa-edit text-orange-500 mr-2"></i>
                填写格式：
              </h5>
              <div class="bg-gray-100 rounded px-3 py-2 font-mono text-sm mb-3">
                fas fa-图标名称
              </div>
              <ul class="text-sm text-gray-600 space-y-1">
                <li>• <code class="bg-gray-200 px-1 rounded">fas</code> 表示实心图标样式</li>
                <li>• <code class="bg-gray-200 px-1 rounded">fa-</code> 是固定前缀</li>
                <li>• 后面跟具体的图标名称</li>
              </ul>
            </div>
          </div>

          <!-- 右侧：常用示例和预览 -->
          <div>
            <!-- 常用示例 -->
            <div class="bg-white rounded-lg p-4 border border-gray-200 mb-4">
              <h5 class="font-semibold text-gray-700 mb-3 flex items-center">
                <i class="fas fa-star text-yellow-500 mr-2"></i>
                常用示例：
              </h5>
              <div class="grid grid-cols-2 gap-2 text-xs">
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded border border-gray-100">
                  <i class="fas fa-book text-blue-500"></i>
                  <code class="text-gray-600">fas fa-book</code>
                </div>
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded border border-gray-100">
                  <i class="fas fa-heart text-red-500"></i>
                  <code class="text-gray-600">fas fa-heart</code>
                </div>
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded border border-gray-100">
                  <i class="fas fa-flask text-green-500"></i>
                  <code class="text-gray-600">fas fa-flask</code>
                </div>
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded border border-gray-100">
                  <i class="fas fa-child text-purple-500"></i>
                  <code class="text-gray-600">fas fa-child</code>
                </div>
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded border border-gray-100">
                  <i class="fas fa-language text-orange-500"></i>
                  <code class="text-gray-600">fas fa-language</code>
                </div>
                <div class="flex items-center space-x-2 p-2 bg-gray-50 rounded border border-gray-100">
                  <i class="fas fa-graduation-cap text-indigo-500"></i>
                  <code class="text-gray-600">fas fa-graduation-cap</code>
                </div>
              </div>
            </div>

            <!-- 实时预览 -->
            <div class="bg-white rounded-lg p-4 border border-gray-200">
              <h5 class="font-semibold text-gray-700 mb-3 flex items-center">
                <i class="fas fa-eye text-pink-500 mr-2"></i>
                实时预览：
              </h5>
              <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                <i :class="categoryForm.icon || 'fas fa-th-large'" class="text-3xl text-primary"></i>
                <div>
                  <div class="text-sm font-medium text-gray-700">
                    {{ categoryForm.icon || 'fas fa-th-large' }}
                  </div>
                  <div class="text-xs text-gray-500">
                    {{ categoryForm.icon ? '图标预览' : '图标预览' }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/admin.js'
import { merchantAPI } from '@/api/merchant.js'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const loading = ref(false)

// 根据用户角色选择API
const currentAPI = computed(() => {
  return userStore.isMerchant ? merchantAPI : adminAPI
})
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

const searchForm = reactive({
  name: '',
  status: ''
})

const categoryForm = reactive({
  id: null,
  name: '',
  parentId: 0,
  icon: '',
  sortOrder: 0,
  status: 1
})

const categoryList = ref([])
const topCategories = ref([])
const iconValidationMessage = ref('')
const iconValidationClass = ref('')

const dialogTitle = computed(() => isEdit.value ? '编辑分类' : '添加分类')

const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '分类名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请输入分类图标', trigger: 'blur' }
  ]
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadCategoryList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm
    }

    const response = await currentAPI.value.getCategoryList(params)
    const categories = response.data.records || []

    // 构建树形结构
    const treeData = buildCategoryTree(categories)
    categoryList.value = treeData
    topCategories.value = categories.filter(item => item.parentId === 0)
  } catch (error) {
    console.error('加载分类列表失败:', error)
    ElMessage.error('加载分类列表失败')
  } finally {
    loading.value = false
  }
}

// 构建分类树形结构
const buildCategoryTree = (categories) => {
  const categoryMap = new Map()
  const rootCategories = []

  // 创建分类映射
  categories.forEach(category => {
    categoryMap.set(category.id, { ...category, children: [] })
  })

  // 构建树形结构
  categories.forEach(category => {
    const categoryNode = categoryMap.get(category.id)

    if (category.parentId === 0) {
      // 顶级分类
      rootCategories.push(categoryNode)
    } else {
      // 子分类
      const parentNode = categoryMap.get(category.parentId)
      if (parentNode) {
        parentNode.children.push(categoryNode)
      }
    }
  })

  return rootCategories
}

const handleSearch = () => {
  loadCategoryList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    name: '',
    status: ''
  })
  handleSearch()
}

const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const showAddSubDialog = (parentCategory) => {
  isEdit.value = false
  categoryForm.parentId = parentCategory.id
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  isEdit.value = true
  Object.assign(categoryForm, { ...row })
  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(categoryForm, {
    id: null,
    name: '',
    parentId: 0,
    icon: '',
    sortOrder: 0,
    status: 1
  })
  iconValidationMessage.value = ''
  iconValidationClass.value = ''
  formRef.value?.resetFields()
}

// 验证图标格式
const validateIcon = () => {
  const icon = categoryForm.icon.trim()

  if (!icon) {
    iconValidationMessage.value = ''
    iconValidationClass.value = ''
    return
  }

  // 检查是否符合 FontAwesome 格式
  const faPattern = /^(fas|far|fab|fal|fad|fat)\s+fa-[a-z0-9-]+$/i

  if (faPattern.test(icon)) {
    iconValidationMessage.value = '✓ 图标格式正确'
    iconValidationClass.value = 'text-green-600'
  } else {
    iconValidationMessage.value = '⚠ 请使用正确的FontAwesome格式，如: fas fa-book'
    iconValidationClass.value = 'text-red-600'
  }
}

// 打开FontAwesome网站
const openFontAwesome = () => {
  window.open('https://fontawesome.com/search', '_blank')
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (isEdit.value) {
      await currentAPI.value.updateCategory(categoryForm.id, categoryForm)
      ElMessage.success('分类更新成功')
    } else {
      await currentAPI.value.createCategory(categoryForm)
      ElMessage.success('分类添加成功')
    }

    dialogVisible.value = false
    resetForm()
    loadCategoryList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

const toggleCategoryStatus = async (row) => {
  try {
    const action = row.status === 1 ? '禁用' : '启用'
    await ElMessageBox.confirm(`确定要${action}分类 "${row.name}" 吗？`, '确认操作')

    const newStatus = row.status === 1 ? 0 : 1
    await currentAPI.value.toggleCategoryStatus(row.id, newStatus)
    row.status = newStatus
    ElMessage.success(`分类${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const deleteCategory = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${row.name}" 吗？`, '确认删除', {
      type: 'warning'
    })

    await currentAPI.value.deleteCategory(row.id)
    ElMessage.success('分类删除成功')
    loadCategoryList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

onMounted(() => {
  loadCategoryList()
})
</script>

<style scoped>
/* 优化树形表格显示 */
:deep(.el-table__expand-icon) {
  color: #409eff;
}

:deep(.el-table__indent) {
  padding-left: 20px;
}

/* 子分类行样式 */
:deep(.el-table__row--level-1) {
  background-color: #f8fafc;
}

:deep(.el-table__row--level-1:hover) {
  background-color: #f1f5f9 !important;
}

/* 优化分类名称显示 */
.el-table .flex.items-center {
  justify-content: flex-start;
}

/* 子分类标签样式 */
.el-tag.el-tag--info.el-tag--small {
  font-size: 10px;
  height: 18px;
  line-height: 16px;
}
</style>
